//
//  H_LoginVC.m
//  Honey
//
//  Created by 贾亚涵 on 16/5/7.
//  Copyright © 2016年 贾亚涵. All rights reserved.
//

#import "H_LoginVC.h"
#import "H_TabBarController.h"
#import "H_BingDVC.h"


#define Login_PnoneNum 520
#define Login_PassWord 525

@interface H_LoginVC ()<UITextFieldDelegate,UIAlertViewDelegate>
{
    UILabel * _backLabel;
    
    
    UIView * _loginMainV;
    UIView * _loginV1;
    UIView * _loginV2;
    UILabel * _loginL1;
    UILabel * _loginL2;
    UITextField * _loginPhoneNumTF;
    UITextField * _loginPassWordTF;
    NSString * _LPhoneNumStr;
    NSString * _LPassWordStr;
    UIButton * _loginBtn;
    NSString *_bgPhone;
}

@end

@implementation H_LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self NaviBarBtn];
    [self createLoginView];
}

-(void)NaviBarBtn
{
    UIImage * leftBarBtnI = [[UIImage imageNamed:@"tl_photo_slide_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftBarBtnI style:UIBarButtonItemStylePlain target:self action:@selector(leftBerBtnClicked)];
    _backLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 0, 60, 40)];
    _backLabel.text = @"返回";
    _backLabel.textColor = [UIColor whiteColor];
    [self.navigationController.navigationBar addSubview:_backLabel];
}

-(void)leftBerBtnClicked
{
    [self loginPackKeyboard];
    //返回主界面
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

-(void)loginPackKeyboard
{
    [_loginPhoneNumTF resignFirstResponder];
    [_loginPassWordTF resignFirstResponder];
}
#pragma UITextFieldDelegate
//点击界面view 触发  收键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_loginPhoneNumTF resignFirstResponder];
    [_loginPassWordTF resignFirstResponder];
}

//初始化登录界面
-(void)createLoginView
{
    _loginMainV = [[UIView alloc] initWithFrame:CGRectMake(0, 64, Screen_Width, 103)];
    _loginMainV.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_loginMainV];
    
    _loginL1 = [self addLoginUILabelWithRect:CGRectMake(0, 1, 90, 50) Text:@"手  机  号 :"];
    [_loginMainV addSubview:_loginL1];
    _loginV1 = [self addUIViewWithRect:CGRectMake(CGRectGetMaxX(_loginL1.frame)+1, 1, Screen_Width-90, 50)];
    [_loginMainV addSubview:_loginV1];
    _loginPhoneNumTF = [self addLoginUITFWithPlaceholder:@"请输入手机号"];
    //设置键盘类型，手机号调用数字键盘
    _loginPhoneNumTF.keyboardType = UIKeyboardTypeNumberPad;
    _loginPhoneNumTF.tag = Login_PnoneNum;
    [_loginV1 addSubview:_loginPhoneNumTF];
    
    _loginL2 = [self addLoginUILabelWithRect:CGRectMake(0, CGRectGetMaxY(_loginL1.frame)+1, 90, 50) Text:@"密        码 :"];
    [_loginMainV addSubview:_loginL2];
    _loginV2 = [self addUIViewWithRect:CGRectMake(CGRectGetMaxX(_loginL2.frame)+1, CGRectGetMaxY(_loginL1.frame)+1, Screen_Width-90, 50)];
    [_loginMainV addSubview:_loginV2];
    _loginPassWordTF = [self addLoginUITFWithPlaceholder:@"请输入密码"];
    _loginPassWordTF.tag = Login_PassWord;
    //设置密文
    _loginPassWordTF.secureTextEntry = YES;
    [_loginV2 addSubview:_loginPassWordTF];
    
    _loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(_loginMainV.frame)+80, Screen_Width-30, 40)];
    [_loginBtn setTitle:@"登 录" forState:UIControlStateNormal];
    _loginBtn.layer.cornerRadius = 8.0f;
    _loginBtn.backgroundColor = [UIColor colorWithRed:246/255.0 green:157/255.0 blue:182/255.0 alpha:1];
    [_loginBtn addTarget:self action:@selector(LoginBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginBtn];
    
}

#pragma mark- addUIlabel
-(UILabel *)addLoginUILabelWithRect:(CGRect)rect Text:(NSString *)text
{
    UILabel * _RLlabel = [[UILabel alloc] initWithFrame:rect];
    _RLlabel.text = text;
    _RLlabel.textAlignment = NSTextAlignmentCenter;
    _RLlabel.textColor = [UIColor grayColor];
    _RLlabel.font = [UIFont systemFontOfSize:15];
    _RLlabel.backgroundColor = [UIColor whiteColor];
    return _RLlabel;
}

#pragma mark- addUITextFiled
-(UITextField *)addLoginUITFWithPlaceholder:(NSString *)placeholder
{
    UITextField * _RLTextFiled = [[UITextField alloc] initWithFrame:CGRectMake(10, 0, Screen_Width-100, 50)];
    _RLTextFiled.backgroundColor = [UIColor whiteColor];
    //关闭首字母自动大写
    _RLTextFiled.autocapitalizationType = UITextAutocapitalizationTypeNone;
    //添加清除小标
    _RLTextFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    _RLTextFiled.placeholder = placeholder;
    [_RLTextFiled addTarget:self action:@selector(RLTFChanged:) forControlEvents:UIControlEventEditingChanged];
    _RLTextFiled.delegate = self;
    return _RLTextFiled;
}
//对注册信息的限制
-(void)RLTFChanged:(UITextField *)sender
{
    switch (sender.tag)
    {
        case Login_PnoneNum:
        {
            NSCharacterSet * CS = [[NSCharacterSet characterSetWithCharactersInString:PhoneCanInput] invertedSet];
            NSString * str = [[_loginPhoneNumTF.text componentsSeparatedByCharactersInSet:CS] componentsJoinedByString:@""];
            
            if (_loginPhoneNumTF.text.length <= 11 && [str isEqualToString:_loginPhoneNumTF.text])
            {
                _LPhoneNumStr = _loginPhoneNumTF.text;
                
            }else
            {
                _loginPhoneNumTF.text = _LPhoneNumStr;
            }
        }
            break;
        case Login_PassWord:
        {
            NSCharacterSet * CS = [[NSCharacterSet characterSetWithCharactersInString:PassWord_Can_Input] invertedSet];
            NSString * str = [[_loginPassWordTF.text componentsSeparatedByCharactersInSet:CS] componentsJoinedByString:@""];
            if (_loginPassWordTF.text.length <= 16 && [str isEqualToString:_loginPassWordTF.text])
            {
                _LPassWordStr = _loginPassWordTF.text;
                
            }else
            {
                _loginPassWordTF.text = _LPassWordStr;
            }
        }
            break;
            
        default:
            break;
    }
}

#pragma mark- UIView
-(UIView *)addUIViewWithRect:(CGRect)rect
{
    UIView * mainV = [[UIView alloc] initWithFrame:rect];
    mainV.backgroundColor = [UIColor whiteColor];
    return mainV;
}

-(void)LoginBtnClicked:(id)sender
{
    if (sender && [sender isKindOfClass:[UIButton class]])
    {
        //收起键盘
        [self loginPackKeyboard];
        //调用提示框第三方
        MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.color = [UIColor orangeColor];
        
        if (_loginPhoneNumTF.text != nil)
        {
            //判断手机号的长度
            if (_loginPhoneNumTF.text.length == 11)
            {
                if ([@"13,15,17,18" containsString:[_loginPhoneNumTF.text substringToIndex:2]])
                {
                    if (_loginPassWordTF.text != nil)
                    {
                        //判断密码的长度
                        if (_loginPassWordTF.text.length >= 6 && _loginPassWordTF.text.length <= 16)
                        {
                            [hud hide:YES];
                            [self checkLoginInfoFromMYData];
                        }else
                        {
                            [hud setMode:MBProgressHUDModeText];
                            [hud setLabelText:@"请输入6到16位密码"];
                            [hud hide:YES afterDelay:1];
                        }
                    }else
                    {
                        [hud setMode:MBProgressHUDModeText];
                        [hud setLabelText:@"请输入密码"];
                        [hud hide:YES afterDelay:1];
                    }
                    
                    
                }else
                {
                    [hud setMode:MBProgressHUDModeText];
                    [hud setLabelText:@"请输入正确的手机号"];
                    [hud hide:YES afterDelay:1];
                    
                }
                
            }else
            {
                [hud setMode:MBProgressHUDModeText];
                [hud setLabelText:@"请输入11位手机号"];
                [hud hide:YES afterDelay:1];
            }
        }else
        {
            [hud setMode:MBProgressHUDModeText];
            [hud setLabelText:@"手机号为空，请输入手机号"];
            [hud hide:YES afterDelay:1];
        }
        
        
    }
}

//登录信息的数据库校对
-(void)checkLoginInfoFromMYData
{
    H_CoreDataDAL * dal2 = [H_CoreDataDAL new];
    //调用第三方提示框
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.color = [UIColor orangeColor];
    if (![dal2 checkLoginInfoPhoneNum:_loginPhoneNumTF.text PassWord:_loginPassWordTF.text])
    {
        [hud setMode:MBProgressHUDModeText];
        [hud setLabelText:@"账号或密码不正确，请确认后重新输入"];
        [hud hide:YES afterDelay:1.5];
        
    }else
    {
        [self checkBDState];
        [hud hide:YES];
    }
    
}

//校对绑定状态
-(void)checkBDState
{
    H_CoreDataDAL * dal = [H_CoreDataDAL new];
    //调用第三方提示框
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.color = [UIColor orangeColor];
    int q;
    q = [dal checkIsBingDPhoneNum:_loginPhoneNumTF.text];
    switch (q) {
        case 0://成功绑定
        {
            //保存登录状态
            H_UserManager * man = [H_UserManager Instance];
            H_UserMemberModel * mm = [H_UserMemberModel new];
            NSString * str = [dal checkBDPhone:_loginPhoneNumTF.text];
            mm.userPhone = _loginPhoneNumTF.text;
            mm.bdUserPhone = str;
            [man saveModel:mm];
            [hud setMode:MBProgressHUDModeText];
            [hud setLabelText:@"登录成功"];
            [hud hide:YES afterDelay:1];
            [self performSelector:@selector(change) withObject:nil afterDelay:1.1];
            
        }
            break;
        case 1://发送申请
        {
            [hud hide:YES];
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"成功发送申请，等待对方接受" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            alert.tag = 600;
            [alert performSelector:@selector(show) withObject:nil afterDelay:0.6];
            
            
        }
            break;
        case 2://接受申请
        {
            NSString *phone = [dal checkBDPhone:_loginPhoneNumTF.text];
            _bgPhone = phone;
            [hud hide:YES];
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"您收到以下好友的绑定申请" message:phone delegate:self cancelButtonTitle:@"接受" otherButtonTitles:@"拒绝", nil];
            alert.tag = 650;
            [alert performSelector:@selector(show) withObject:nil afterDelay:0.6];
        }
            break;
        case 3://未绑定
        {
            [hud hide:YES];
            
            H_BingDVC * bdVC = [H_BingDVC new];
            //进入绑定界面把登录的号进行传值
            bdVC.phoneNum = _loginPhoneNumTF.text;
            [self.navigationController pushViewController:bdVC animated:YES];
        }
            break;
        default:
            break;
    }
    
}


#pragma mark- UIAlertView
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 600) {
        [self dismissViewControllerAnimated:YES completion:^{
        }];
    }
    else{
        if (buttonIndex == 0) {
            //接受
            H_CoreDataDAL * dal = [H_CoreDataDAL new];
            [dal beApplyForPhone:_loginPhoneNumTF.text bdPhone:_bgPhone B:YES];
            MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.color = [UIColor orangeColor];
            //保存登录状态
            H_UserManager * man = [H_UserManager Instance];
            H_UserMemberModel * mm = [H_UserMemberModel new];
            NSString * str = [dal checkBDPhone:_loginPhoneNumTF.text];
            mm.userPhone = _loginPhoneNumTF.text;
            mm.bdUserPhone = str;
            [man saveModel:mm];
            [hud setMode:MBProgressHUDModeText];
            [hud setLabelText:@"绑定成功"];
            [hud hide:YES afterDelay:1];
            [self performSelector:@selector(change) withObject:nil afterDelay:1.1];
        }
        else{
            //拒绝
            H_CoreDataDAL * dal = [H_CoreDataDAL new];
            [dal beApplyForPhone:_loginPhoneNumTF.text bdPhone:_bgPhone B:NO];
            
            //返回主界面
            [self dismissViewControllerAnimated:YES completion:^{
            }];

        }
    }
    
}

//登录成功进入应用界面0
-(void)change
{
    H_TabBarController * tabBar = [H_TabBarController new];
    [UIApplication sharedApplication].keyWindow.rootViewController = tabBar;
    
}

@end
